﻿using System.Collections.Generic;
using UnityEngine;

namespace Space3D
{
    public class AABBTree
    {
        /// <summary>
        /// 一个叶子结点最多包含的Poly数
        /// </summary>
        public readonly int LEAF_POLY_MAX_COUNT = 1;
        public AABBNode rootAABB;
        public int nodeCount = 0;
        public int maxDepth = 0;

        /// <summary>
        /// List<Vector3>是Poly的边界顶点坐标，按顺时针
        /// List<List<Vector3>>指多个Poly
        /// </summary>
        /// <param name="polys"></param>
        public AABBTree(List<List<Vector3>> polys)
        {
            if (polys.Count > 0)
            {
                rootAABB = new AABBNode(this, polys);
            }
            else
            {
                rootAABB = new AABBNode(this);
                rootAABB.polys = new List<List<Vector3>>(); //叶子结点，空Poly列表
            }
        }

        /// <summary>
        /// 遍历ABT
        /// </summary>
        /// <param name="hitTest"></param>
        /// <returns></returns>
        public List<AABBNode> Traverse(NodeTest hitTest)
        {
            var hits = new List<AABBNode>();
            Traverse(rootAABB, hitTest, hits);
            return hits;
        }
        private void Traverse(AABBNode curNode, NodeTest hitTest, List<AABBNode> hitlist)
        {
            if (curNode == null)
            {
                return;
            }
            if (hitTest(curNode))
            {
                hitlist.Add(curNode);
                Traverse(curNode.left, hitTest, hitlist);
                Traverse(curNode.right, hitTest, hitlist);
            }
        }
    }

    public delegate bool NodeTest(AABBNode box);
}